<?php
namespace app\home\controller\user;

use app\BaseController;

use app\common\model\TouziLotteryRecord;
use app\common\model\TouziLotteryTimes;
use app\common\model\UserAddress;
use app\common\model\MoneyLog;
use app\common\model\PayWithdraw;
use app\common\model\UserBank;
use app\common\model\UserRealName;
use app\common\model\PayRecharge;
use app\common\model\SysConfig;
use app\common\model\TouziFanyongLog;
use app\common\model\TouziGainSendLog;
use app\common\model\TeamTongji;
use app\common\model\TouziKLine;
use app\common\model\TouziProductOrder;
use app\common\model\TouziQianDao;
use app\common\model\PayChannel;
use app\common\model\User;
use app\common\model\User as models;

use app\common\service\RealName;
use app\common\service\Pay;
use app\common\logic\Sms;
use app\common\traites\PublicCrudTrait;

use think\exception\ValidateException;
use think\Request; // ✅ 使用实例类，不是 facade
use think\facade\Db;
use think\Response;

use hg\apidoc\annotation as Apidoc;

/**
 *
 * @Apidoc\Title("个人中心")
 * */
class Member extends BaseController
{
    protected $model;
    use PublicCrudTrait;

    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 更新用户头像
     */
    public function updateAvatar(Request $request): Response
    {
        $userId = $request->post('user_id');
        $url = $request->post('avatar');

        if (empty($userId) || empty($url)) {
            return show([], config('ToConfig.http_code.error'), '缺少必要参数 user_id 或 url');
        }

        try {
            $result = Db::name('common_user')
                ->where('id', $userId)
                ->update(['avatar' => $url]);

            if ($result === 0) {
                return show([], config('ToConfig.http_code.error'), '用户不存在或头像未改变');
            }

            return show(['avatar' => $url]);
        } catch (\Exception $e) {
            return show([], config('ToConfig.http_code.error'), $e->getMessage());
        }
    }
    /**
     * @Apidoc\Title("修改用昵称")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("nickname", type="string",require=true, desc="昵称")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function update_nickname_tencent(Request $request): Response
    {
        $userId = $request->post('user_id');
        $nickname = $request->post('nickname');
        //过滤数据
        $postField = 'user_id,nickname';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            $this->validate($post,[
                'nickname' => 'require|max:200', //
            ],
                [
                    'nickname' => 'please fill in the user nickname in the correct format',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }

        $result = Db::name('common_user')
                ->where('id', $userId)
                ->update(['nickname' => $nickname]);
        if ($result === 0) {
            return show([],config('ToConfig.http_code.error'),'更新昵称失败');
            
        }else{
            return show([]);
        }
    }
    /**
     * @Apidoc\Title("用户的个人信息")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function user_info()
    {
        $uid= session('home_user.id');
        $home_user= $this->model->field('*')->where('id',$uid)->find();
        $home_user['true_name'] = getTrueName($uid);
        $home_user['card_id'] = getTrueNameID($uid);
        $home_user['nickname'] = ($home_user['true_name']!='')?$home_user['true_name']:$home_user['phone'];
        $home_user['invitation_link'] = config('ToConfig.app_update.app_qrcode').$home_user['invitation_code'];
        // 增加购买产品 类型 数量统计
        $home_user['buy_product_nums'] = $this->getBuyProductNums($uid);
        // 增加购买产品 类型 数量统计
        $home_user['buy_product_zhifu_nums'] = $this->getBuyProductZhiFuNums($uid);

        // 如果二维码 文件 不存在 重新生成
        @$f = file_get_contents($home_user['qrCodeImg']);
        if(!$f){
            $register_url = config('ToConfig.app_update.app_qrcode').$home_user['invitation_code'];
            $img = generate($register_url);
            $this->model->where('id',$uid)->save(['qrCodeImg'=>config('ToConfig.app_update.erweim_url').$img]);
        }
        // 结束了

        if (empty($home_user)) return show([],config('ToConfig.http_code.error'),'Re login');
        return show($home_user);
    }

    protected function getBuyProductNums($uid){
        $nums = 0;
        $map = [];
        $map['user_id'] = $uid;
        $map['class_type_id'] = 2;
        $orderNums = (new TouziProductOrder())->where($map)->count();
        if($orderNums > 0){
            $nums = $orderNums;
        }
        return $nums;
    }

    protected function getBuyProductZhiFuNums($uid){
        $nums = 0;
        $map = [];
        $map['user_id'] = $uid;
        $map['class_type_id'] = 3;
        // $map[] = ['create_time','>=','2024-12-15 00:00:00'];
        $orderNums = (new TouziProductOrder())->where($map)->whereTime('create_time', '>=', '2024-12-15 00:00:00')->count();
        if($orderNums > 0){
            $nums = $orderNums;
        }
        return $nums;
    }

    /**
     * @Apidoc\Title("成为vip")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function be_vip()
    {
        $uid= session('home_user.id');
        $home_user= $this->model->field('*')->where('id',$uid)->find();
        // 检测是否 VIP
        if ($home_user['vip_grade']==1){
            return show([],config('ToConfig.http_code.error'),'已经是vip');
        } 
        // 检测余额是否够用
        if($home_user['money_balance']<66){
            return show([],config('ToConfig.http_code.error'),'余额不足');
        }

        // //写入记录
        // $draw_times = 5;
        // $times = [
        //     'user_id' => $uid,
        //     'send_times' => $draw_times,
        //     'create_time' => date('Y-m-d H:i:s'),
        //     'mark' => '成为爱心大使赠送抽奖次数',
        // ];
        // TouziLotteryTimes::create($times);
        // //增加抽奖次数
        // User::increaseBy('choujiang_times', $uid, $draw_times);

        // 更新vip 
        $this->model->where('id',$uid)->dec('money_balance',66)->update(['vip_grade'=>1]);
        // 返回结果
        return show([]);
    }



    /**
     * @Apidoc\Title("分享信息")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function fenxiang(){
        $uid= session('home_user.id');
        $res = (new TeamTongji())->where('user_id',$uid)->find();
        $data = [
            'avatar' => 'avatar',
            'user_name' => 'user_name',
            'qrCodeImg' => 'qrCodeImg',
            'mineLink' => 'mineLink'
        ];
        return show($data);
    }



    /**
     * @Apidoc\Title("修改密码")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("old_pwd", type="string",require=true, desc="老密码")
     * @Apidoc\Param("pwd", type="string",require=true, desc="新密码")
     * @Apidoc\Param("pwd_again", type="string",require=true, desc="新密码重复")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function update_pwd(){
        $uid= session('home_user.id');
        //过滤数据
        $postField = 'old_pwd,pwd,pwd_again';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            $this->validate($post,[
                'old_pwd' => 'require|max:200', //
                'pwd' => 'require|max:200', //
                'pwd_again' => 'require|max:200', //
            ],
                [
                    'old_pwd' => 'please fill in the original password in the correct format',
                    'pwd' => 'please fill in a new password in the correct format',
                    'pwd_again' => 'please fill in the new password in the correct format again',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        $User=new User();
        $user=$User->where('id',$uid)->find();
        // 原始密码 错误
        // if($user['withdraw_pwd'] != 'aa123456'){
        //     if (pwdEncryption($post['withdraw_old_pwd'])!=$user['withdraw_pwd']){
        //         return show([],config('ToConfig.http_code.error'),'原始密码错误');
        //     }
        // }
        // 两次 密码一致
        if ($post['pwd']!=$post['pwd_again']){
            return show([],config('ToConfig.http_code.error'),'two new passwords are inconsistent');
        }
        // 新旧密码一致
        if (pwdEncryption($post['pwd'])==$user['pwd']){
            return show([],config('ToConfig.http_code.error'),'new password cannot be the same as the original password');
        }
        // 更新
        $res=$User->where('id',$uid)->save(['pwd'=>pwdEncryption($post['pwd'])]);
        if ($res){
            return show([]);
        }else{
            return show([],config('ToConfig.http_code.error'),'modification failed');
        }
    }

    /**
     * @Apidoc\Title("修改用昵称")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("nickname", type="string",require=true, desc="昵称")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function update_nickname(){
        $uid= session('home_user.id');
        //过滤数据
        $postField = 'nickname';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            $this->validate($post,[
                'nickname' => 'require|max:200', //
            ],
                [
                    'nickname' => 'please fill in the user nickname in the correct format',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        $User=new User();
        $res=$User->where('id',$uid)->save(['nickname'=>$post['nickname']]);
        if ($res){
            return show([]);
        }else{
            return show([],config('ToConfig.http_code.error'),'fail');
        }
    }

    /**
     * @Apidoc\Title("修改性别")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("sex", type="string",require=true, desc="性别 0 女 1 男")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function update_sex(){
        $uid= session('home_user.id');
        //过滤数据
        $postField = 'sex';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            $this->validate($post,[
                'sex' => 'require|max:200', //
            ],
                [
                    'sex' => 'please fill in the user sex in the correct format',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        $User=new User();
        $res=$User->where('id',$uid)->save(['sex'=>$post['sex']]);
        if ($res){
            return show([]);
        }else{
            return show([],config('ToConfig.http_code.error'),'fail');
        }
    }

    /**
     * @Apidoc\Title("设置交易密码")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("withdraw_pwd", type="string",require=true, desc="提现密码")
     * @Apidoc\Param("sms_code", type="string",require=true, desc="短信")
     * @Apidoc\Param("withdraw_pwd_again", type="string",require=true, desc="提醒密码重复")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function update_withdraw_pwd(){
        $uid= session('home_user.id');
        //过滤数据
        $postField = 'withdraw_pwd,sms_code,withdraw_pwd_again,withdraw_old_pwd';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            // $this->validate($post,[
            //     'withdraw_pwd' => 'require|max:20', //
            //     'withdraw_pwd_again' => 'require|max:20', //
            //     'sms_code' => 'require|number|max:6', //
            // ],
            //     [
            //         'withdraw_pwd' =>'please fill in the withdraw password in the correct format',
            //         'withdraw_pwd_again' =>'please fill in the withdraw password in the correct format',
            //         'sms_code' => 'please fill in the SMS verification code with correct format',
            //     ]
            // );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        $User=new User();
        $user=$User->where('id',$uid)->find();
        //检测短信验证码
        $sms=new Sms();
        $res_sms=$sms->checkCode(3,$user['phone'],$post['sms_code']);
        if ($res_sms['status']==0){
            return show([],config('ToConfig.http_code.error'),$res_sms['msg']);
        }
        // 检测两次 密码 是否 一致
        if ($post['withdraw_pwd']!=$post['withdraw_pwd_again']){
            return show([],config('ToConfig.http_code.error'),'两次密码不一致');
        }
        // 新旧密码 是否一致
        if (pwdEncryption($post['withdraw_pwd'])==$user['withdraw_pwd']){
            return show([],config('ToConfig.http_code.error'),'新旧密码一致，没有修改');
        }

        $User=new User();
        $user=$User->where('id',$uid)->find();
        if(!$post['sms_code']){
                // 原始密码 错误
            if (pwdEncryption($post['withdraw_old_pwd'])!=$user['withdraw_pwd']){
                return show([],config('ToConfig.http_code.error'),'原始密码错误');
            }
        }
        

        // 支付密码
        $res=$User->where('id',$uid)->save(['withdraw_pwd'=>pwdEncryption($post['withdraw_pwd'])]);
        // 执行插入
        if ($res){
            return show([]);
        }else{
            return show([],config('ToConfig.http_code.error'),'修改失败');
        }
    }

    /**
     * @Apidoc\Title("修改提现密码 获取短信验证码 之前的图型码")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("captcha", type="string",require=true, desc="提现发短信的图形验证码")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function withdraw_captcha(){
        $uid= session('home_user.id');
        //过滤数据
        $postField = 'captcha';
        $post      = $this->request->only(explode(',', $postField), 'post', null);
        try {
            $this->validate($post,[
                'captcha' => 'max:5', //
            ],
                [
                    'captcha' => 'please fill in the correct format verification code',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        //检测验证码
        // if (!captcha_check($post['captcha'])) {
        //     return show([],config('ToConfig.http_code.error'),'code error');
        // }
        //检测账号
        $User=new User();
        $user=$User->where('id',$uid)->find();
        $sms=new Sms();
        $ip=$this->request->ip();
        $res=$sms->sendCode($ip,3,$user['phone']);

        if ($res['status']==1){
            return show([]);
        }else{
            return show([],config('ToConfig.http_code.error'),$res['msg']);
        }
    }

    /**
     * @Apidoc\Title("文件上传接口")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", type="file",require=true, desc="文件")
     * @Apidoc\Returned("savename", type="array", desc="保存文件路径")
     */
    public function uploads(){
        $files = request()->file('file');
        if (empty($files)) return $this->failed('Uploaded file not detected');
        $savename = '';
        try {
            validate(['image'=>'fileSize:102400|fileExt:jpg,gpg,png'])->check((array)$files);
            $path =\think\facade\Filesystem::disk("public")->putFile("topic",$files);
            $savename=\think\Facade\Filesystem::getDiskConfig('public', 'url').'/'.str_replace('\\', '/', $path);
        } catch (\think\exception\ValidateException $e) {
            return show([],config('ToConfig.http_code.error'),$e->getMessage());
        }
        if (empty($savename)) return show([],config('ToConfig.http_code.error'),'upload fail');
        return show($savename);
    }
    /**
     * 更新用户背景图接口
     * POST /home/user/update/{userId}
     */
    public function update($userId)
    {
        // 获取请求参数
        $data = Request::only(['comments_bg'], 'post');

        if (empty($data['comments_bg'])) {
            return json([
                'code' => 400,
                'message' => '参数 comments_bg 不能为空'
            ]);
        }

        // 更新数据库 common_user 表
        $updated = Db::name('common_user')
            ->where('id', $userId)
            ->update(['comments_bg' => $data['comments_bg']]);

        if ($updated) {
            return json([
                'code' => 200,
                'message' => '背景图更新成功',
                'data' => ['comments_bg' => $data['comments_bg']]
            ]);
        } else {
            return json([
                'code' => 500,
                'message' => '更新失败或数据未变更'
            ]);
        }
    }
    /**
     * @Apidoc\Title("下级购买 返佣记录")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("page", type="string",require=true, desc="页面")
     * @Apidoc\Param("limit", type="string",require=true, desc="分页限制")
     * @Apidoc\Param("start", type="string",require=true, desc="开始时间 可以不写")
     * @Apidoc\Param("end", type="string",require=true, desc="结束时间 可以不写")
     * @Apidoc\Returned("data", type="array", desc="返回数据")
     */
    public function fanyong_records(){
        $uid= session('home_user.id');
        //过滤数据
        // $postField = 'page,limit,start,end';
        // $post   = $this->request->only(explode(',', $postField), 'post', null);

        $page = $this->request->post('page', 1);//当前页
        $limit = $this->request->post('limit', 10);//每页显示数量
        $start = $this->request->post('start'); // 搜索开始时间
        $end = $this->request->post('end'); // 搜索结束时间
        $date = [];
        if(!empty($start) && !empty($end)){
            $date['start'] = $start;
            $date['end'] = $end;
        }

        $map = [];
        $map['user_id']= $uid;
        $res=(new TouziFanyongLog())->page_list($map,$limit,$page,$date);
        return show($res);
    }


    /**
     * @Apidoc\Title("退出登录")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="bool", desc="返回成功失败结果")
     */
    public function sign_out()
    {
        $session = session('home_user');
        $token = $session['token'];
        // 清除数据库 token
        HomeToken::where('token', $token)->delete();
        session('home_user', null);
        return show();
    }
// 类结束了
}
